package cn.bluarry.lbstest;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    public LocationClient locationClient;

    private TextView positionText;

    private MapView mapView;

    private  BaiduMap baiduMap;

    private boolean isFirstLocate=true;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());
        locationClient=new LocationClient(getApplicationContext());
        locationClient.registerLocationListener(new MyLocationListener());
        setContentView(R.layout.activity_main);
        positionText=findViewById(R.id.position_text_view);
        mapView=findViewById(R.id.bmapView);

        baiduMap=mapView.getMap();
        baiduMap.setMyLocationEnabled(true);

        List<String> permissList=new ArrayList<>();
        if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED){
            permissList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.READ_PHONE_STATE)!=PackageManager.PERMISSION_GRANTED){
            permissList.add(Manifest.permission.READ_PHONE_STATE);
        }
        if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){
            permissList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if(!permissList.isEmpty()){
            String[] perm=permissList.toArray(new String[permissList.size()]);
            ActivityCompat.requestPermissions(MainActivity.this,perm,1);
        }else{
            requestlocation();
        }
    }

    private void requestlocation(){
        initLocation();
        locationClient.start();
    }
    private void initLocation(){
        LocationClientOption option=new LocationClientOption();
        //option.setLocationMode(LocationClientOption.LocationMode.Device_Sensors);
        option.setIsNeedAddress(true);
        option.setScanSpan(5000);
        locationClient.setLocOption(option);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        locationClient.stop();
        mapView.onDestroy();
        baiduMap.setMyLocationEnabled(false);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 1:
                if(grantResults.length>0){
                    for(int r : grantResults){
                        if(r!=PackageManager.PERMISSION_GRANTED){
                            Toast.makeText(MainActivity.this,"error无法运行",Toast.LENGTH_SHORT).show();
                            finish();
                            return;
                        }
                    }
                    requestlocation();
                }else{
                    Toast.makeText(MainActivity.this,"无法运行",Toast.LENGTH_SHORT).show();
                    finish();
                }

                break;
        default:
            break;
        }
    }

    private void navigateto(BDLocation bdLocation){
        if(isFirstLocate){
            LatLng ll=new LatLng(bdLocation.getLatitude(),bdLocation.getLongitude());
            MapStatusUpdate ud=MapStatusUpdateFactory.newLatLng(ll);
            baiduMap.animateMapStatus(ud);
            ud=MapStatusUpdateFactory.zoomTo(16f);
            baiduMap.animateMapStatus(ud);
            isFirstLocate=false;
        }
    }


    public class MyLocationListener implements BDLocationListener{

        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
                //第一种，操作textview
//            StringBuilder currentpos=new StringBuilder();
//            currentpos.append("维度: ").append(bdLocation.getLatitude()).append('\n');
//            currentpos.append("经度: ").append(bdLocation.getLongitude()).append('\n');
//            currentpos.append("国家: ").append(bdLocation.getCountry()).append('\n');
//            currentpos.append("省: ").append(bdLocation.getProvince()).append('\n');
//            currentpos.append("市: ").append(bdLocation.getCity()).append('\n');
//            currentpos.append("区: ").append(bdLocation.getDistrict()).append('\n');
//            currentpos.append("街道: ").append(bdLocation.getStreet()).append('\n');
//
//            currentpos.append("定位方式: ");
//            if(bdLocation.getLocType()==BDLocation.TypeGpsLocation){
//                currentpos.append("GPS");
//            }else if(bdLocation.getLocType()==BDLocation.TypeNetWorkLocation){
//                currentpos.append("网络");
//            }
//            positionText.setText(currentpos);
//          操作mapview
            if(bdLocation.getLocType()==BDLocation.TypeGpsLocation ||bdLocation.getLocType()==BDLocation.TypeNetWorkLocation ){
                navigateto(bdLocation);
            }
            MyLocationData.Builder bd=new MyLocationData.Builder();
            bd.latitude(bdLocation.getLatitude());
            bd.longitude(bdLocation.getLongitude());
            MyLocationData d=bd.build();
            baiduMap.setMyLocationData(d);

        }
    }



}
